<template>
  <uni-drawer ref="userDrawer" mode="right" :mask-click="true" :width="330" :height="100">
    <view class="header">
      <search ref="sea" @confirm="confirmSearch" />
      <view class="title">
        <view class="inline-item">
          <text>通讯录</text>
        </view>
      </view>
    </view>
    <view>
      <scroll-view
        scroll-y="true"
        class="user-scroll-wrap"
        lower-threshold="50"
        @scrolltolower="touchBottom"
        @touchmove.stop
      >
        <view class="container-list">
          <u-gap bgColor="#F5F5F5" height="8"> </u-gap>
          <view
            class="common"
            v-for="(item, index) in userListData"
            @click="handleUserClick(item, index)"
            :key="item.staffId"
          >
            <label class="info-content">
              <view class="uni-inline-item">
                <view>
                  <image
                    v-if="isUserSelect(item)"
                    class="select-icon"
                    src="/static/images/work/dbd/selected_yes.png"
                    mode="aspectFit"
                  ></image>
                  <image
                    v-else
                    class="select-icon"
                    src="/static/images/work/dbd/selected_no.png"
                    mode="aspectFit"
                  ></image>
                </view>
                <view class="user-icon-wrap">
                  <image v-if="item.avatar" class="user-icon" :src="staticUrl + item.avatar" mode="aspectFit"> </image>
                  <image v-else class="user-icon" src="/static/images/default_avatar_icon.png" mode="aspectFit">
                  </image>
                </view>
                <view class="dept-name"> {{ item.staffName }}</view>
              </view>
              <view class="uni-inline-item" v-if="item.children">
                <view class="user-num">{{ item.userCount }}</view>
                <u-icon name="arrow-right" size="12" color="#999999"></u-icon>
              </view>
            </label>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="btn box_sizing">
      <!-- 单选底部信息 -->
      <view class="bottom-btn-wrap">
        <view class="selected-text" v-if="userCheckList.length > 0"> 已选择：{{ userCheckList[0].staffName }} </view>
        <view class="selected-text" v-else>未选择</view>
        <button class="confirm-btn" type="primary" @click.stop="backConfirm">确定</button>
      </view>
    </view>
  </uni-drawer>
</template>

<script>
import search from './search/index.vue'
import { listUserPaging } from '@/api/system/user.js'
import { staticUrl } from '@/config.js'
import { contractorAccUsrList, contractorUsrList } from '../../api/system/user'

export default {
  name: 'UserSelector',
  components: {
    search
  },
  props: {
    /*1本企业 2承包商*/
    userType: {
      type: [Number, String],
      default: ''
    },
    isContractorAccUsr: {
      type: [Boolean, String],
      default: ''
    },
    deptId: {
      type: [Number, String],
      default: ''
    },
    // 排除的用户ID
    excludeIds: {
      type: Array,
      default: () => {
        return []
      }
    },
    postName: {
      type: String,
      default: ''
    },
    multiple: {
      type: [Boolean, String],
      default: ''
    },
    // 拓展字段
    expandFields: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    // 用户是否选中
    isUserSelect() {
      return (item) => {
        const userCheckList = this.userCheckList
        if (userCheckList.length == 0) {
          return false
        }
        const i =
          userCheckList.findIndex((e) => {
            return item.staffId == e.staffId
          }) > -1
        return i
      }
    }
  },
  data() {
    return {
      staticUrl,
      searchKey: '',
      userListData: [],
      listData: [],
      pageNum: 1,
      isFinished: false,
      total: null,
      userCheckList: [], // 已选中用户数据
      temp: []
    }
  },
  created() {
    this.initData()
  },
  methods: {
    //搜索
    async confirmSearch(val) {
      this.searchKey = val
      this.initData()
    },
    touchBottom() {
      if (this.isFinished) {
        return
      }
      this.pageNum++
      this.getItemList()
    },
    initData() {
      this.userListData = []
      this.listData = []
      this.isFinished = false
      this.pageNum = 1
      this.total = null
      this.getItemList()
    },
    getItemList() {
      if (this.isFinished) {
        return
      }
      if (!this.total || this.total > this.listData.length) {
        const data = {
          ...this.expandFields,
          // deptId: this.deptId,
          keyword: this.searchKey,
          postName: this.postName,
          pageNum: this.pageNum
        }
        if (this.userType === '2') {
          data.userType = this.userType
          data.filterBlackList = true
          if (this.isContractorAccUsr) data.thirdId = this.deptId
          else data.contractorId = this.deptId
        } else {
          data.deptId = this.deptId
        }

        // console.log('isContractorAccUsr', this.isContractorAccUsr)
        let apiList = [listUserPaging, contractorUsrList, contractorAccUsrList]
        let api = null
        if (this.userType === '2') {
          api = this.isContractorAccUsr ? apiList[2] : apiList[1]
        } else {
          api = apiList[0]
        }
        api(data)
          .then((res) => {
            if (res.data) {
              res.rows = res.data
            }
            /*
             * 内部人员、承包商用户、承包商有账号用户字段各不一样
             * 需要统一处理
             * */
            if (this.userType === '2' && !this.isContractorAccUsr) {
              res.rows.map((r) => {
                r.staffId = r.id
              })
            }
            let arr = []
            for (var i = 0; i < res.rows.length; i++) {
              if (this.excludeIds.indexOf(res.rows[i].staffId) == -1) {
                arr.push(res.rows[i])
              }
            }
            if (this.pageNum === 1) {
              this.userListData = arr
              this.listData = res.rows
            } else {
              this.userListData.push(...arr)
              this.listData.push(...res.rows)
            }
            this.total = res.total
            this.isFinished = this.listData.length === res.total
          })
          .finally(() => {
            uni.stopPullDownRefresh()
          })
      }
    },
    open(staffId) {
      this.temp = []
      if (!staffId) {
        this.userCheckList = []
      } else {
        this.userCheckList = [staffId]
      }
      this.searchKey = ''
      this.initData()
      this.$refs.userDrawer.open()
    },
    // 人员点击处理
    handleUserClick(item, index) {
      this.userRadioClick(item, index)
    },
    async backConfirm() {
      let dataObj = {}
      let dataArr = []

      if (this.userCheckList.length) {
        if (this.multiple) {
          for (const user of this.userCheckList) {
            let u = {
              name: user.staffName,
              staffId: user.staffId
            }
            dataArr.push(u)
          }
          this.$emit('change', dataArr)
        } else {
          dataObj = {
            name: this.userCheckList[0].staffName,
            value: this.userCheckList[0].staffId
          }
          this.$emit('change', dataObj)
        }
      }
      this.$refs.userDrawer.close()
    },
    // 人员单选
    userRadioClick(item, index) {
      console.log('item', item)
      console.log('multiple', this.multiple)

      if (this.multiple) {
        let bi = this.temp.findIndex((t) => {
          return t.staffId === item.staffId
        })
        if (bi > -1) {
          this.temp.splice(bi, 1)
        } else {
          this.temp.push(item)
        }
        this.$set(this, 'userCheckList', this.temp)
      } else {
        this.$set(this, 'userCheckList', [
          {
            ...item
          }
        ])
      }
      console.log('userCheckList', this.userCheckList)
    }
  }
}
</script>
<style lang="scss" scoped>
@import './css/style.scss';
</style>
